<script lang="ts" setup>
// Api增删改查接口
import { addData, findPage, remove, updateData, search } from "@@/apis/ofd/OfdCategoryApis";
// Http请求全局参数数据类型
import {PageParam, SearchSortPageParam} from "@@/types/http";
// Http请求专用参数和请求结果数据类型
import {
	OfdCategoryCreateOrUpdateParam,
	OfdCategorySearchParam,
	OfdCategoryOrderParam,
	type OfdCategoryResult
} from "@/types/OfdCategory";
// 文件上传组件
import Upload from "@@/components/trade/Upload.vue";
// 文件工具
import { getFullUrl } from "@@/utils/file";
// 分页组件
import { usePagination } from "@@/composables/usePagination";

// Element-plus图标类型
import { CirclePlus, Delete, Download, Refresh, RefreshRight, Search, } from "@element-plus/icons-vue";
// Element-plus数据类型
import type { FormInstance, FormRules, UploadFile, UploadProps, UploadRawFile } from "element-plus";
// 深度拷贝函数
import { cloneDeep } from "lodash-es";
// 导出excel的函数
import { export_json_to_excel } from "@/common/utils/excel/Export2Excel.js";

defineOptions({
	// 命名当前组件
	name: "OfdCategory",
});

// 列表加载状态
const loading = ref<boolean>(false);
// 导出动画状态
const downloadLoading = ref<boolean>(false);
// 分页数据
const {paginationData, handleCurrentChange, handleSizeChange} = usePagination();
// 默认表单数据
const DEFAULT_FORM_DATA: OfdCategoryCreateOrUpdateParam = {
	id: -1,
			code: 0,
			name: '',
			img: '',
			createTime: 0,
			updateTime: 0,
			isDeleted: 0,
};

// 列表数据
const tableData = ref<{ data: OfdCategoryResult[] }>({
  data: [],
});

// 对话框显示开关
const dialogVisible = ref<boolean>(false);
// 表单数据
const formRef = ref<FormInstance | null>(null);
// 表单数据 深拷贝默认数据
const formData = ref<OfdCategoryCreateOrUpdateParam>(cloneDeep(DEFAULT_FORM_DATA));
// 表单校验规则
const formRules: FormRules<OfdCategoryCreateOrUpdateParam> = {
	// title: [{ required: true, trigger: "blur", message: "请输入标题" }],
	// ...
};

// #region 增删改查
/**
* 新增或者修改
*/
function handleCreateOrUpdate() {
	// 表单校验
	formRef.value?.validate((valid: any) => {
		if (!valid) {
			ElMessage.error("表单校验不通过");
		return;
	}
	// 显示加载框
	loading.value = true;
	// 判断是否有id,以此确定是新增还是修改
	let isCreate = formData.value.id === undefined || formData.value.id === null || formData.value.id === -1;
	// 默认修改
	let callCreateOrUpdateApi = updateData
	let createOrUpdate = "修改";
	// 如果是新增，修改数据
	if(isCreate){
		callCreateOrUpdateApi = addData;
		createOrUpdate = "新增";
	}

	// 重构参数
	let param = new OfdCategoryCreateOrUpdateParam(
				Number(formData.value.id),
				Number(formData.value.code),
				formData.value.name,
				formData.value.img,
				Number(formData.value.createTime),
				Number(formData.value.updateTime),
				Number(formData.value.isDeleted),

	)

	// 调用接口
	callCreateOrUpdateApi(param)
		// 请求成功 res为数据结构 NetResult(code,msg,data)
		.then(({data}) => {
			// 判断是否成功
			const isSuccess = data.value;
			console.log(isSuccess);
			if (isSuccess) {
				// 提示成功
				ElMessage.success("数据" + createOrUpdate + "操作成功");
				// 关闭对话框
				dialogVisible.value = false;
				// 查询分页数据
				handleFindPage();
			}
			})
			.finally(() => {
				// 关闭加载框
				loading.value = false;
		});
	});
}

/**
* 删除
* @param row
*/
function handleRemove(row: OfdCategoryResult) {
	ElMessageBox.confirm(`正在删除数据：${row.id}，确认删除？`, "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		// 调用接口
		remove({id: row.id}).then(() => {
			ElMessage.success("删除成功");
			// 查询分页数据
			handleFindPage();
		});
	});
}

/**
* 修改
* @param row
*/
function handleUpdate(row: OfdCategoryResult) {
	// 弹出对话框
	dialogVisible.value = true;
	// 深拷贝 当前行数据
  formData.value = cloneDeep(row);
  console.log("handleUpdate-row-img", row.img);
  console.log("handleUpdate-formData-img", formData.value.img);
	// 待实现
}

/**
* 分页查询
*/
function handleFindPage() {
	loading.value = true;
	const page = paginationData.currentPage;
	const pageSize = paginationData.pageSize;
	const body = new PageParam(page, pageSize);
	// 调用接口
	findPage(body)
		.then(({data}) => {
			// 设置数据池总数
			paginationData.total = data.total;
			// 设置表格数据
			tableData.value.data = data.dataList;
		})
		.catch(() => {
			// 表格数据置空
			tableData.value.data = [];
		})
		.finally(() => {
			// 关闭加载框
			loading.value = false;
	});
}

// #endregion

// 搜索
const searchFormRef = ref<FormInstance | null>(null);
// 搜索表单数据
const searchData = reactive<OfdCategorySearchParam>(new OfdCategorySearchParam());

// 处理搜索
function handleSearch() {
	if (paginationData.currentPage === 1) {
		callSearchApi();
	} else {
		paginationData.currentPage = 1;
	}
}

// 调用搜索接口
function callSearchApi() {
	loading.value = true;
	const page = paginationData.currentPage;
	const pageSize = paginationData.pageSize;

	const body: SearchSortPageParam<OfdCategorySearchParam, OfdCategoryOrderParam> = new SearchSortPageParam(
		new PageParam(page, pageSize),
		searchData,
		new OfdCategoryOrderParam(0, 0, 0, 0, 0, 0, 0, 0, )
	)

	// 调用接口
	search(body)
		.then(({data}) => {
			// 设置数据池总数
			paginationData.total = data.total;
			// 设置表格数据
			tableData.value.data = data.dataList;
		})
		.catch(() => {
			// 表格数据置空
			tableData.value.data = [];
		})
		.finally(() => {
			// 关闭加载框
			loading.value = false;
		});
}

// 重置搜索表单
function resetSearch() {
	searchFormRef.value?.resetFields();
	handleSearch();
}

// #region 上传图片
const imageUrl = ref("");

const uploadRef = ref(null);

		/**
		* 上传img图片后，更新图片地址
		* Upload子组件上传图片后，让父组件更新图片地址
		* @param url
		*/
		const updateImgUrl = (url: string) => {
			console.log("parent-updateImgUrl", url);
			formData.value.img = url;
		};

// 上传图片成功后的回调函数
const handleUploadSuccess: UploadProps["onSuccess"] = (response: any, uploadFile: UploadFile) => {
	imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

// 上传图片前的校验
const beforeUpload: UploadProps["beforeUpload"] = (rawFile: UploadRawFile) => {
	if (rawFile.type !== "image/jpeg") {
		ElMessage.error("Avatar picture must be JPG format!");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("Avatar picture size can not exceed 2MB!");
		return false;
	}
	return true;
};

// 重置表单
function resetForm() {
	formRef.value?.clearValidate();
	console.log("DEFAULT_FORM_DATA", DEFAULT_FORM_DATA);
	formData.value = cloneDeep(DEFAULT_FORM_DATA);
}
// #endregion

// region 导出excel
// 导出excel
function exportToExcel() {
	downloadLoading.value = true;
	const title = '食品分类列表';
	const tHeader = [
		'主键',
		'编码',
		'名称',
		'图片',
		'创建时间',
		'更新时间',
		'是否删除',
		'状态',
	];
	const filtervals = [
			'id',
			'code',
			'name',
			'img',
			'createTime',
			'updateTime',
			'isDeleted',
			'status',
	];
	const data=formatJson(filtervals,tableData.value.data);
		export_json_to_excel({
		header: tHeader,
		data,
		filename: title
	} as ExcelExportData & Parameters<typeof export_json_to_excel>[0])
	downloadLoading.value = false;
}

// 格式化json
function formatJson(filterVal:Array<any>, jsonData:Array<any>) {
	return jsonData.map(v => filterVal.map(j => v[j]))
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], handleFindPage, {
		immediate: true,
});
</script>

<template>
  <div class="app-container">
    <!--搜索表单-->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="code" label="编码">
          <el-input v-model="searchData.code" placeholder="请输入编码..." />
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="searchData.name" placeholder="请输入名称..." />
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间">
          <el-input v-model="searchData.createTime" placeholder="请输入创建时间..." />
        </el-form-item>
        <el-form-item prop="updateTime" label="更新时间">
          <el-input v-model="searchData.updateTime" placeholder="请输入更新时间..." />
        </el-form-item>
        <el-form-item prop="isDeleted" label="是否删除">
          <el-input v-model="searchData.isDeleted" placeholder="请输入是否删除..." />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!--表格操作栏-->
    <el-card v-loading="loading" shadow="never">
      <!--表格操作条-->
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增
          </el-button>
          <el-button type="danger" :icon="Delete"> 批量删除 </el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" @click="exportToExcel" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button
              type="primary"
              :icon="RefreshRight"
              circle
              @click="handleFindPage"
            />
          </el-tooltip>
        </div>
      </div>

      <!--表格-->
      <div class="table-wrapper">
        <el-table :data="tableData.data">
          <el-table-column prop="code" label="编码" align="center" />
          <el-table-column prop="name" label="名称" align="center" />
          <el-table-column prop="img" label="图片" align="center">
            <template #default="scope">
              <el-image
                :src="getFullUrl(scope.row.img)"
                fit="cover"
                alt=""
                :preview-src-list="[getFullUrl(scope.row.img)]"
                style="width: 48px; height: 48px; border-radius: 10%"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column prop="isDeleted" label="是否删除" align="center" />
          <el-table-column prop="status" label="数据状态" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.status === 0"
                type="success"
                effect="plain"
                disable-transitions
              >
                正常
              </el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>
                已删除
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
              >
                修改
              </el-button>
              <el-button
                type="danger"
                text
                bg
                size="small"
                @click="handleRemove(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页条 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增和修改对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="
        formData.id === null || formData.id === undefined || formData.id === -1
          ? '新增食品分类'
          : '修改食品分类'
      "
      width="30%"
      @closed="resetForm"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item prop="code" label="编码">
          <el-input v-model="formData.code" placeholder="请输入编码..." />
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="formData.name" placeholder="请输入名称..." />
        </el-form-item>
        <el-form-item prop="img" label="图片">
          <upload
            ref="uploadRef"
            :form-data="formData"
            :image-url="formData.img"
            :update-url="updateImgUrl"
          />
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间">
          <el-input v-model="formData.createTime" placeholder="请输入创建时间..." />
        </el-form-item>
        <el-form-item prop="updateTime" label="更新时间">
          <el-input v-model="formData.updateTime" placeholder="请输入更新时间..." />
        </el-form-item>
        <el-form-item prop="isDeleted" label="是否删除">
          <el-input v-model="formData.isDeleted" placeholder="请输入是否删除..." />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

// 页面宏样式
<style lang="scss" scoped="scoped">
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
